package com.hwadee.property.controller.util;

import com.hwadee.property.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/file")
@Api(tags = "文件-FileController", description = "文件操作相关接口")
@CrossOrigin
public class FileController {
    @Autowired
    private FileUtil fileUtil;

    @GetMapping
    @ApiOperation(value = "【用户】根据绝对路径获取服务器文件", notes = "根据绝对路径获取服务器文件")
    public ResponseEntity<Resource> getFile(@RequestParam String path) {
        try {
            // 获取文件的输入流
            InputStream inputStream = fileUtil.getFileInputStream(path);
            // 获取文件名
            String fileName = fileUtil.getFileName(path);

            // 根据文件扩展名设置 Content-Type
            MediaType contentType = getContentType(fileName);

            // 创建一个输入流资源
            InputStreamResource fileAsResource = new InputStreamResource(inputStream);

            // 对文件名进行编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            // 设置响应头
            return ResponseEntity.ok()
                    .contentType(contentType)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName)
                    .body(fileAsResource);
        } catch (Exception e) {
            // 如果发生异常，返回错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    private MediaType getContentType(String fileName) {
        String extension = fileUtil.getFileExtension(fileName).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return MediaType.IMAGE_JPEG;
            case "png":
                return MediaType.IMAGE_PNG;
            case "pdf":
                return MediaType.APPLICATION_PDF;
            case "txt":
                return MediaType.TEXT_PLAIN;
            default:
                return MediaType.APPLICATION_OCTET_STREAM;
        }
    }
}
